package article_api

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/res"
	"giv-vue-blog/service/common"
	"giv-vue-blog/utils/jwts"
)

type CollResponse struct {
	models.ArticleModel
	CreatedAt string `json:"created_at"`
}

// ArticleCollListView 文章收藏列表
// @Summary 获取文章收藏列表
// @Description 获取用户收藏的文章列表，并按照收藏时间倒序排序
// @Tags 文章管理
// @Produce json
// @Param page query int false "页码，默认为1"
// @Param pageSize query int false "每页显示的数量，默认为10"
// @Success 200 {object} res.Response{}
// @Router /api/articles/collect [get]
func (ArticleApi) ArticleCollListView(c *gin.Context) {
	var cr models.PageInfo
	_ = c.ShouldBindQuery(&cr)
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.CustomClaims)

	var articleIDList []interface{}
	list, count, err := common.CommonList(models.UserCollectModel{UserID: claims.UserID}, common.Option{
		PageInfo: cr,
	})
	var collMap = map[string]string{}
	for _, model := range list {
		articleIDList = append(articleIDList, model.ArticleID)
		collMap[model.ArticleID] = model.CreatedAt.Format("2006-01-02 15:04:05")
	}
	//传id列表 查es
	// 查询
	boolSearch := elastic.NewTermsQuery("_id", articleIDList...)
	var collList = make([]CollResponse, 0)
	result, err := global.EsClient.
		Search(models.ArticleModel{}.Index()).
		Query(boolSearch).
		Highlight(elastic.NewHighlight().Field("title")). //文章高亮搜索
		//方法一 不显示content，它只会把这个内容在界面上渲染为空 因此采用另一种方法 在结构体中content字段后添加omit(list) 当在list时会把这个字段给去掉
		//FetchSourceContext(elastic.NewFetchSourceContext(true).Exclude("content")).
		Size(1000).
		Do(context.Background())
	if err != nil {
		res.FailedWithMsg(err.Error(), c)
		return
	}
	for _, hit := range result.Hits.Hits {
		var article models.ArticleModel
		err = json.Unmarshal(hit.Source, &article)
		if err != nil {
			global.Log.Error(err)
			continue
		}
		article.ID = hit.Id
		collList = append(collList, CollResponse{
			ArticleModel: article,
			CreatedAt:    collMap[hit.Id],
		})
	}
	res.OkWithList(collList, count, c)
}
